/************************************************************
 *  * Hyphenate CONFIDENTIAL
 * __________________
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 *
 * NOTICE: All information contained herein is, and remains
 * the property of Hyphenate Inc.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Hyphenate Inc.
 */

#import "ChatDemoHelper.h"
#import "ContactDataObject.h"
#import <AudioToolbox/AudioToolbox.h>
#import "AppDelegate.h"
//#import "ApplyViewController.h"
#import "MBProgressHUD.h"

#import "EaseSDKHelper.h"

#ifdef REDPACKET_AVALABLE
#import "RedpacketOpenConst.h"
#import "RedPacketUserConfig.h"
#endif

#if DEMO_CALL == 1
#import "DemoCallManager.h"
#endif

static ChatDemoHelper *helper = nil;

@implementation ChatDemoHelper

+ (instancetype)shareHelper
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        helper = [[ChatDemoHelper alloc] init];
    });
    return helper;
}

- (void)dealloc
{
    [[EMClient sharedClient] removeDelegate:self];
    [[EMClient sharedClient].groupManager removeDelegate:self];
    [[EMClient sharedClient].contactManager removeDelegate:self];
    [[EMClient sharedClient].roomManager removeDelegate:self];
    [[EMClient sharedClient].chatManager removeDelegate:self];
}

- (id)init
{
    self = [super init];
    if (self) {
        [self initHelper];
    }
    return self;
}


#pragma mark - init

- (void)initHelper
{
#ifdef REDPACKET_AVALABLE
    [[RedPacketUserConfig sharedConfig] beginObserveMessage];
#endif
    
    [[EMClient sharedClient] addDelegate:self delegateQueue:nil];
    [[EMClient sharedClient].groupManager addDelegate:self delegateQueue:nil];
    [[EMClient sharedClient].contactManager addDelegate:self delegateQueue:nil];
    [[EMClient sharedClient].roomManager addDelegate:self delegateQueue:nil];
    [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
    
#if DEMO_CALL == 1
    [DemoCallManager sharedManager];
#endif
}

- (void)asyncPushOptions
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        EMError *error = nil;
        [[EMClient sharedClient] getPushOptionsFromServerWithError:&error];
    });
}

- (void)asyncGroupFromServer {
//    __weak typeof(self) weakself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [[EMClient sharedClient].groupManager getJoinedGroups];
        EMError *error = nil;
        [[EMClient sharedClient].groupManager getMyGroupsFromServerWithError:&error];
//        if (!error) {
//            if (weakself.contactViewVC) {
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    [weakself.contactViewVC reloadGroupView];
//                });
//            }
//        }
    });
}

- (void)asyncConversationFromDB {
    __weak typeof(self) weakself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSArray *array = [[EMClient sharedClient].chatManager getAllConversations];
        [array enumerateObjectsUsingBlock:^(EMConversation *conversation, NSUInteger idx, BOOL *stop){
            if(conversation.latestMessage == nil){
                [[EMClient sharedClient].chatManager deleteConversation:conversation.conversationId isDeleteMessages:NO completion:nil];
            }
        }];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (weakself.chatMessTableView) {
                [weakself.chatMessTableView tableViewDidTriggerHeaderRefresh];
            }
            
            if (weakself.chatMessTableView) {
//                [weakself.chatMessTableView setupUnreadMessageCount];
//                [(AppDelegate *)[UIApplication sharedApplication].delegate setupUnreadMessageCount];
            }
        });
    });
}

#pragma mark - EMClientDelegate

// 网络状态变化回调
- (void)connectionStateDidChange:(EMConnectionState)aConnectionState {
////    [self.mainVC networkChanged:connectionState];
}


- (void)autoLoginDidCompleteWithError:(EMError *)error {
    if (error) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"自动登录失败，请重新登录" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alertView.tag = 100;
        [alertView show];
    } else if([[EMClient sharedClient] isConnected]){
//        UIView *view = self.mainVC.view;
//        [MBProgressHUD showHUDAddedTo:view animated:YES];
//        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//            BOOL flag = [[EMClient sharedClient] migrateDatabaseToLatestSDK];
//            if (flag) {
//                [self asyncGroupFromServer];
//                [self asyncConversationFromDB];
//            }
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [MBProgressHUD hideAllHUDsForView:view animated:YES];
//            });
//        });
    }
}

- (void)userAccountDidLoginFromOtherDevice {
    [self _clearHelper];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"提示", @"Prompt") message:NSLocalizedString(@"您的账号在其他设备登录", @"your login account has been in other places") delegate:self cancelButtonTitle:NSLocalizedString(@"确定", @"OK") otherButtonTitles:nil, nil];
    alertView.tag = 10000033;
    [alertView show];
    if (_chatMessTableView) {
        [_chatMessTableView tableViewDidTriggerHeaderRefresh];
    }
//    [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 10000033) {
//        [(AppDelegate *)[UIApplication sharedApplication].delegate gotoLogin:0];
    }
}

- (void)userAccountDidRemoveFromServer {
    [self _clearHelper];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"prompt", @"Prompt") message:NSLocalizedString(@"loginUserRemoveFromServer", @"your account has been removed from the server side") delegate:self cancelButtonTitle:NSLocalizedString(@"ok", @"OK") otherButtonTitles:nil, nil];
    [alertView show];
    [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
}

- (void)userDidForbidByServer {
    [self _clearHelper];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"prompt", @"Prompt") message:NSLocalizedString(@"servingIsBanned", @"Serving is banned") delegate:self cancelButtonTitle:NSLocalizedString(@"ok", @"OK") otherButtonTitles:nil, nil];
    [alertView show];
    [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
}

//- (void)didServersChanged
//{
//    [self _clearHelper];
//    [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
//}
//
//- (void)didAppkeyChanged
//{
//    [self _clearHelper];
//    [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
//}

#pragma mark - EMChatManagerDelegate

- (void)didUpdateConversationList:(NSArray *)aConversationList {
    if (self.chatMessTableView) {
//        [self.chatMessTableView setupUnreadMessageCount];
//        [(AppDelegate *)[UIApplication sharedApplication].delegate setupUnreadMessageCount];
    }
    if (self.chatMessTableView) {
        [_chatMessTableView tableViewDidTriggerHeaderRefresh];
    }
}

- (void)messagesDidReceive:(NSArray *)aMessages {
    BOOL isRefreshCons = YES;
    [self storeUser:aMessages];
    for(EMMessage *message in aMessages){
        BOOL needShowNotification = (message.chatType != EMChatTypeChat) ? [self _needShowNotification:message.conversationId] : YES;
        
#ifdef REDPACKET_AVALABLE
        /**
         *  屏蔽红包被抢消息的提示
         */
        NSDictionary *dict = message.ext;
        needShowNotification = (dict && [dict valueForKey:RedpacketKeyRedpacketTakenMessageSign]) ? NO : needShowNotification;
#endif

        UIApplicationState state = [[UIApplication sharedApplication] applicationState];
        if (needShowNotification) {
        
#if !TARGET_IPHONE_SIMULATOR
            switch (state) {
                case UIApplicationStateActive:
                    break;
                case UIApplicationStateInactive:
                    break;
                case UIApplicationStateBackground:
                    [self showNotificationWithMessage:message];
                    break;
                default:
                    break;
            }
#endif
        }
        
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        BOOL isMessage = [userDefaults boolForKey:@"messageVC"];
        if (!isMessage) {
            [[EMCDDeviceManager sharedInstance]playNewMessageSound];
        }
        BOOL isChatting = NO;
        if (isChatting) {
        }
//        AudioServicesPlaySystemSound(1007);
        
        if (!isChatting || state == UIApplicationStateBackground) {
            [self _handleReceivedAtMessage:message];
            if (self.chatMessTableView) {
                [_chatMessTableView tableViewDidTriggerHeaderRefresh];
            }
            
            if (self.chatMessTableView) {
//                [self.chatMessTableView setupUnreadMessageCount];
//                [(AppDelegate *)[UIApplication sharedApplication].delegate setupUnreadMessageCount];
            }
            return;
        }
        
        if (isChatting) {
            isRefreshCons = NO;
        }
    }
    
    if (isRefreshCons) {
        if (self.chatMessTableView) {
            [_chatMessTableView tableViewDidTriggerHeaderRefresh];
        }
        if (self.chatMessTableView) {
//            [self.chatMessTableView setupUnreadMessageCount];
//            [(AppDelegate *)[UIApplication sharedApplication].delegate setupUnreadMessageCount];

        }
    }
    
}

- (void)storeUser:(NSArray *)messages {
    //    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    [messages enumerateObjectsUsingBlock:^(EMMessage *message, NSUInteger idx, BOOL * _Nonnull stop) {
        [[ContactDataObject shareInstance]queryEasemobuserid:message.ext];
    }];
    //    });
    
    //    SystemSoundID soundID;
    //    NSString *strSoundFile = [[NSBundle mainBundle] pathForResource:@"alertsound" ofType:@"wav"];
    //    AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:strSoundFile],&soundID);
    
//    [(AppDelegate *)[UIApplication sharedApplication].delegate setupUnreadMessageCount];
}


#pragma mark - EMGroupManagerDelegate

- (void)didReceiveLeavedGroup:(EMGroup *)aGroup
                       reason:(EMGroupLeaveReason)aReason {
    NSString *str = nil;
    if (aReason == EMGroupLeaveReasonBeRemoved) {
        str = [NSString stringWithFormat:@"Your are kicked out from group: %@ [%@]", aGroup.subject, aGroup.groupId];
    } else if (aReason == EMGroupLeaveReasonDestroyed) {
        str = [NSString stringWithFormat:@"Group: %@ [%@] is destroyed", aGroup.subject, aGroup.groupId];
    }
    
//    if (str.length > 0) {
//        TTAlertNoTitle(str);
//    }
//    
//    NSMutableArray *viewControllers = [NSMutableArray arrayWithArray:_mainVC.navigationController.viewControllers];
//    ChatViewController *chatViewContrller = nil;
//    for (id viewController in viewControllers)
//    {
//        if ([viewController isKindOfClass:[ChatViewController class]] && [aGroup.groupId isEqualToString:[(ChatViewController *)viewController conversation].conversationId])
//        {
//            chatViewContrller = viewController;
//            break;
//        }
//    }
//    if (chatViewContrller)
//    {
//        [viewControllers removeObject:chatViewContrller];
//        if ([viewControllers count] > 0) {
//            [_mainVC.navigationController setViewControllers:@[viewControllers[0]] animated:YES];
//        } else {
//            [_mainVC.navigationController setViewControllers:viewControllers animated:YES];
//        }
//    }
}

- (void)didReceiveJoinGroupApplication:(EMGroup *)aGroup applicant:(NSString *)aApplicant reason:(NSString *)aReason {
    if (!aGroup || !aApplicant) {
        return;
    }
    if (!aReason || aReason.length == 0) {
        aReason = [NSString stringWithFormat:NSLocalizedString(@"group.applyJoin", @"%@ apply to join groups\'%@\'"), aApplicant, aGroup.subject];
    }
    else{
        aReason = [NSString stringWithFormat:NSLocalizedString(@"group.applyJoinWithName", @"%@ apply to join groups\'%@\'：%@"), aApplicant, aGroup.subject, aReason];
    }
    
//    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:@{@"title":aGroup.subject, @"groupId":aGroup.groupId, @"username":aApplicant, @"groupname":aGroup.subject, @"applyMessage":aReason, @"applyStyle":[NSNumber numberWithInteger:ApplyStyleJoinGroup]}];
//    [[ApplyViewController shareController] addNewApply:dic];
//    if (self.mainVC) {
//        [self.mainVC setupUntreatedApplyCount];
//#if !TARGET_IPHONE_SIMULATOR
//        [self.mainVC playSoundAndVibration];
//#endif
//    }
//    
//    if (self.contactViewVC) {
//        [self.contactViewVC reloadApplyView];
//    }
}

- (void)didJoinedGroup:(EMGroup *)aGroup
               inviter:(NSString *)aInviter
               message:(NSString *)aMessage {
//    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"prompt", @"Prompt") message:[NSString stringWithFormat:@"%@ invite you to group: %@ [%@]", aInviter, aGroup.subject, aGroup.groupId] delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", @"OK") otherButtonTitles:nil, nil];
//    [alertView show];
}

- (void)didReceiveDeclinedJoinGroup:(NSString *)aGroupId
                             reason:(NSString *)aReason
{
    if (!aReason || aReason.length == 0) {
        aReason = [NSString stringWithFormat:NSLocalizedString(@"group.beRefusedToJoin", @"be refused to join the group\'%@\'"), aGroupId];
    }
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"prompt", @"Prompt") message:aReason delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", @"OK") otherButtonTitles:nil, nil];
    [alertView show];
}

- (void)didReceiveAcceptedJoinGroup:(EMGroup *)aGroup {
    NSString *message = [NSString stringWithFormat:NSLocalizedString(@"group.agreedAndJoined", @"agreed to join the group of \'%@\'"), aGroup.subject];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"prompt", @"Prompt") message:message delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", @"OK") otherButtonTitles:nil, nil];
    [alertView show];
}

- (void)didReceiveGroupInvitation:(NSString *)aGroupId inviter:(NSString *)aInviter message:(NSString *)aMessage {
    if (!aGroupId || !aInviter) {
        return;
    }
    
//    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:@{@"title":@"", @"groupId":aGroupId, @"username":aInviter, @"groupname":@"", @"applyMessage":aMessage, @"applyStyle":[NSNumber numberWithInteger:ApplyStyleGroupInvitation]}];
//    [[ApplyViewController shareController] addNewApply:dic];
//    if (self.mainVC) {
//        [self.mainVC setupUntreatedApplyCount];
//#if !TARGET_IPHONE_SIMULATOR
//        [self.mainVC playSoundAndVibration];
//#endif
//    }
//    
//    if (self.contactViewVC) {
//        [self.contactViewVC reloadApplyView];
//    }
}

#pragma mark - EMContactManagerDelegate

- (void)didReceiveAgreedFromUsername:(NSString *)aUsername {
    NSString *msgstr = [NSString stringWithFormat:@"%@同意了加好友申请", aUsername];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:msgstr delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alertView show];
}

- (void)didReceiveDeclinedFromUsername:(NSString *)aUsername {
    NSString *msgstr = [NSString stringWithFormat:@"%@拒绝了加好友申请", aUsername];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:msgstr delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alertView show];
}

- (void)didReceiveDeletedFromUsername:(NSString *)aUsername {
//    NSMutableArray *viewControllers = [NSMutableArray arrayWithArray:_mainVC.navigationController.viewControllers];
//    ChatViewController *chatViewContrller = nil;
//    for (id viewController in viewControllers) {
//        if ([viewController isKindOfClass:[ChatViewController class]] && [aUsername isEqualToString:[(ChatViewController *)viewController conversation].conversationId]) {
//            chatViewContrller = viewController;
//            break;
//        }
//    }
//    if (chatViewContrller) {
//        [viewControllers removeObject:chatViewContrller];
//        if ([viewControllers count] > 0) {
//            [_mainVC.navigationController setViewControllers:@[viewControllers[0]] animated:YES];
//        } else {
//            [_mainVC.navigationController setViewControllers:viewControllers animated:YES];
//        }
//    }
//    [_mainVC showHint:[NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"delete", @"delete"), aUsername]];
//    [_contactViewVC reloadDataSource];
}

- (void)didReceiveAddedFromUsername:(NSString *)aUsername
{
//    [_contactViewVC reloadDataSource];
}

- (void)didReceiveFriendInvitationFromUsername:(NSString *)aUsername message:(NSString *)aMessage {
//    if (!aUsername) {
//        return;
//    }
//    if (!aMessage) {
//        aMessage = [NSString stringWithFormat:NSLocalizedString(@"friend.somebodyAddWithName", @"%@ add you as a friend"), aUsername];
//    }
//    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:@{@"title":aUsername, @"username":aUsername, @"applyMessage":aMessage, @"applyStyle":[NSNumber numberWithInteger:ApplyStyleFriend]}];
//    [[ApplyViewController shareController] addNewApply:dic];
//    if (self.mainVC) {
//        [self.mainVC setupUntreatedApplyCount];
//#if !TARGET_IPHONE_SIMULATOR
//        [self.mainVC playSoundAndVibration];
//        
//        BOOL isAppActivity = [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive;
//        if (!isAppActivity) {
//            //发送本地推送
//            if (NSClassFromString(@"UNUserNotificationCenter")) {
//                UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:0.01 repeats:NO];
//                UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
//                content.sound = [UNNotificationSound defaultSound];
//                content.body =[NSString stringWithFormat:NSLocalizedString(@"friend.somebodyAddWithName", @"%@ add you as a friend"), aUsername];
//                UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:[[NSNumber numberWithDouble:[NSDate timeIntervalSinceReferenceDate] * 1000] stringValue] content:content trigger:trigger];
//                [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:nil];
//            }
//            else {
//                UILocalNotification *notification = [[UILocalNotification alloc] init];
//                notification.fireDate = [NSDate date]; //触发通知的时间
//                notification.alertBody = [NSString stringWithFormat:NSLocalizedString(@"friend.somebodyAddWithName", @"%@ add you as a friend"), aUsername];
//                notification.alertAction = NSLocalizedString(@"open", @"Open");
//                notification.timeZone = [NSTimeZone defaultTimeZone];
//            }
//        }
//#endif
//    }
//    [_contactViewVC reloadApplyView];
}

#pragma mark - EMChatroomManagerDelegate

- (void)didReceiveUserJoinedChatroom:(EMChatroom *)aChatroom username:(NSString *)aUsername
{
    
}

- (void)didReceiveUserLeavedChatroom:(EMChatroom *)aChatroom username:(NSString *)aUsername
{

}

- (void)didReceiveKickedFromChatroom:(EMChatroom *)aChatroom  reason:(EMChatroomBeKickedReason)aReason {
    
}

#pragma mark - public

#pragma mark - private
- (BOOL)_needShowNotification:(NSString *)fromChatter
{
    BOOL ret = YES;
    NSArray *igGroupIds = [[EMClient sharedClient].groupManager getGroupsWithoutPushNotification:nil];
    for (NSString *str in igGroupIds) {
        if ([str isEqualToString:fromChatter]) {
            ret = NO;
            break;
        }
    }
    return ret;
}

//- (ChatViewController*)_getCurrentChatView {
//    NSMutableArray *viewControllers = [NSMutableArray arrayWithArray:_mainVC.navigationController.viewControllers];
//    ChatViewController *chatViewContrller = nil;
//    for (id viewController in viewControllers) {
//        if ([viewController isKindOfClass:[ChatViewController class]]) {
//            chatViewContrller = viewController;
//            break;
//        }
//    }
//    return chatViewContrller;
//}

- (void)_clearHelper {
//    self.mainVC = nil;
    self.chatMessTableView = nil;
    self.easeMessageVC = nil;
//    self.chatVC = nil;
//    self.contactViewVC = nil;
    SGUserModel *model = [[SGUserModel alloc] init];
    model = nil;
    [SGUserInfo saveUserInfo:model];
    [[EMClient sharedClient] logout:NO];
}

- (void)_handleReceivedAtMessage:(EMMessage*)aMessage {
    if (aMessage.chatType != EMChatTypeGroupChat || aMessage.direction != EMMessageDirectionReceive) {
        return;
    }
    
    NSString *loginUser = [EMClient sharedClient].currentUsername;
    NSDictionary *ext = aMessage.ext;
    EMConversation *conversation = [[EMClient sharedClient].chatManager getConversation:aMessage.conversationId type:EMConversationTypeGroupChat createIfNotExist:NO];
    if (loginUser && conversation && ext && [ext objectForKey:kGroupMessageAtList]) {
        id target = [ext objectForKey:kGroupMessageAtList];
        if ([target isKindOfClass:[NSString class]] && [(NSString*)target compare:kGroupMessageAtAll options:NSCaseInsensitiveSearch] == NSOrderedSame) {
            NSNumber *atAll = conversation.ext[kHaveUnreadAtMessage];
            if ([atAll intValue] != kAtAllMessage) {
                NSMutableDictionary *conversationExt = conversation.ext ? [conversation.ext mutableCopy] : [NSMutableDictionary dictionary];
                [conversationExt removeObjectForKey:kHaveUnreadAtMessage];
                [conversationExt setObject:@kAtAllMessage forKey:kHaveUnreadAtMessage];
                conversation.ext = conversationExt;
            }
        }
        else if ([target isKindOfClass:[NSArray class]]) {
            if ([target containsObject:loginUser]) {
                if (conversation.ext[kHaveUnreadAtMessage] == nil) {
                    NSMutableDictionary *conversationExt = conversation.ext ? [conversation.ext mutableCopy] : [NSMutableDictionary dictionary];
                    [conversationExt setObject:@kAtYouMessage forKey:kHaveUnreadAtMessage];
                    conversation.ext = conversationExt;
                }
            }
        }
    }
}

- (void)didJoinGroup:(EMGroup *)aGroup
             inviter:(NSString *)aInviter
             message:(NSString *)aMessage {
    NSDictionary *dic = @{@"easemobuserId":aGroup.groupId,@"userName":aGroup.subject,@"logo":@""};
    [[ContactDataObject shareInstance]queryEasemobuserid:dic];
    [[BHAlertUtil alertManager]showPromptInfo:@"有人邀请你入群"];
}

#pragma mark - 发送本地通知
- (void)showNotificationWithMessage:(EMMessage *)message {
    
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    // 设置触发通知的时间
    NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:0];
    NSLog(@"fireDate=%@",fireDate);
    
    notification.fireDate = fireDate;
    // 时区
    notification.timeZone = [NSTimeZone defaultTimeZone];
    // 设置重复的间隔
    //    notification.repeatInterval = kCFCalendarUnitSecond;
    
    // 通知内容
    NSDictionary *dic = [[ContactDataObject shareInstance]queryEasemobuserid:message.conversationId];
    NSString *alertBodyStr = [NSString stringWithFormat:@"%@：%@",dic[@"userName"],[self _latestMessageTitle:message]];
    notification.alertBody = alertBodyStr;
//    notification.applicationIconBadgeNumber = 1;
    // 通知被触发时播放的声音
    notification.soundName = UILocalNotificationDefaultSoundName;
    // 通知参数
    NSDictionary *userDict = [NSDictionary dictionaryWithObject:@"开始学习iOS开发了" forKey:@"key"];
    notification.userInfo = userDict;
    
    // ios8后，需要添加这个注册，才能得到授权
    if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
        UIUserNotificationType type =  UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type
                                                                                 categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        // 通知重复提示的单位，可以是天、周、月
        //                notification.repeatInterval = NSCalendarUnitDay;
    } else {
        // 通知重复提示的单位，可以是天、周、月
        //        notification.repeatInterval = NSDayCalendarUnit;
    }
    // 执行通知注册
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    [self applicationIconBadgeNumber];
}

- (NSString *)_latestMessageTitle:(EMMessage *)message {
    NSString *latestMessageTitle = @"";
    if (message) {
        EMMessageBody *messageBody = message.body;
        switch (messageBody.type) {
            case EMMessageBodyTypeImage:{
                latestMessageTitle = NSEaseLocalizedString(@"图片消息", @"[image]");
            } break;
            case EMMessageBodyTypeText:{
                NSString *didReceiveText = [EaseConvertToCommonEmoticonsHelper
                                            convertToSystemEmoticons:((EMTextMessageBody *)messageBody).text];
                latestMessageTitle = didReceiveText;
            } break;
            case EMMessageBodyTypeVoice:{
                latestMessageTitle = NSEaseLocalizedString(@"音频消息", @"[voice]");
            } break;
            case EMMessageBodyTypeLocation: {
                latestMessageTitle = NSEaseLocalizedString(@"位置消息", @"[location]");
            } break;
            case EMMessageBodyTypeVideo: {
                latestMessageTitle = NSEaseLocalizedString(@"视频消息", @"[video]");
            } break;
            case EMMessageBodyTypeFile: {
                latestMessageTitle = NSEaseLocalizedString(@"文件消息", @"[file]");
            } break;
            default: {
            } break;
        }
    }
    return latestMessageTitle;
}
- (void)applicationIconBadgeNumber {
    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
    NSInteger unreadCount = 0;
    for (EMConversation *conversation in conversations) {
        unreadCount += conversation.unreadMessagesCount;
    }
    [UIApplication sharedApplication].applicationIconBadgeNumber = unreadCount;
}


@end
